package apig.core;

import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Iterator;
import java.util.List;

import javax.management.RuntimeErrorException;
import javax.naming.spi.DirStateFactory.Result;

public class CodeIds implements Iterable<Integer> {

	private final int codeId;
	private List<Integer> codes = null;

	public CodeIds(int codeId) {
		this.codeId = codeId;
	}

	@Override
	public synchronized Iterator<Integer> iterator() {
		if (codes == null)
			try {
				codes = Collections.unmodifiableList(getCodeList());
			} catch (SQLException e) {
				throw new RuntimeException(e);
			}
		return codes.iterator();
	}

	private List<Integer> getCodeList() throws SQLException {
		List<Integer> list = new ArrayList<Integer>();
		try (Connection c = ServerThings.getThings().getConnection();
				Statement st = c.createStatement();) {
			ResultSet rs = st
					.executeQuery("select c1.code_id from codes c1, codes c2 where c1.code_id < "
							+ codeId
							+ " and c2.code_id = "
							+ codeId
							+ " and c1.user_id != c2.user_id");
			while (rs.next())
				list.add(rs.getInt(1));
		}
		return list;
	}
}
